package net.strandbygaard.android.owdroid;

import java.util.List;

import net.strandbygaard.onewire.device.OwId;
import net.strandbygaard.onewire.device.OwSensor;
import net.strandbygaard.onewire.device.OwSensor.Reading;
import net.strandbygaard.onewire.owclient.OwClient;

import org.owfs.ownet.OWNet;

import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.widget.SimpleCursorAdapter;

public class Home extends ListActivity {

	private static final int ACTIVITY_CREATE = 0;
	private static final int ACTIVITY_EDIT = 1;

	private static final int INSERT_ID = Menu.FIRST;
	private static final int DELETE_ID = Menu.FIRST + 1;

	private ReadingsDbAdapter mDbHelper;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		mDbHelper = new ReadingsDbAdapter(this);
		mDbHelper.reset();
		mDbHelper.open();

		OwClient owc = new OwClient(new OWNet("10.0.0.10", 8080));
		List<OwSensor> list = owc.list();

		if (list != null) {
			for (OwSensor dev : list) {
				OwId id = dev.getId();

				String temp = "";
				if (dev.canRead(Reading.TEMP)) {
					temp = Double.toString(dev.read(Reading.TEMP));
					temp = temp.substring(0, temp.indexOf(".") + 2);
					temp = temp + dev.getUnit(Reading.TEMP);
				}

				String hum = "";
				if (dev.canRead(Reading.HUM)) {
					hum = Double.toString(dev.read(Reading.HUM));
					hum = hum.substring(0, hum.indexOf(".") + 2);
					hum = hum + dev.getUnit(Reading.HUM);
				}

				mDbHelper.createReading(id.getId(), "x", id.getId(), temp, hum);
			}
		}
		// mDbHelper.createReading("26.8C48B6000000", "B", "Vaskekælder",
		// "20C", "63%");
		// mDbHelper.createReading("26.8C48B6000000", "C", "Baghave", "17C",
		// "65%");
		// mDbHelper.createReading("10", "A", "sample", "22C", "60%");
		updateReadings();

	}

	private void updateReadings() {
		// Get all of the rows from the database and create the item list
		Cursor readingsCursor = mDbHelper.fetchAllReadings();
		startManagingCursor(readingsCursor);

		// Create an array to specify the fields we want to display in the list
		// (only TITLE)
		String[] from = new String[] { ReadingsDbAdapter.KEY_NUMBER,
				ReadingsDbAdapter.KEY_LOCATION,
				ReadingsDbAdapter.KEY_TEMPERATURE,
				ReadingsDbAdapter.KEY_HUMIDITY };

		// and an array of the fields we want to bind those fields to (in this
		// case just text1)
		int[] to = new int[] { R.id.devNumber, R.id.devLocation,
				R.id.devTemperature, R.id.devHumidity };

		// Now create a simple cursor adapter and set it to display
		SimpleCursorAdapter notes = new SimpleCursorAdapter(this,
				R.layout.readings_row, readingsCursor, from, to);
		setListAdapter(notes);
	}
}